package com.princess.demok.ui.demo

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.princess.baselib.utils.setOnClickListenerWithTrigger
import com.princess.demok.R
import com.princess.demok.base.view.MyBaseActivity
import com.princess.demok.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_compress.*

/**
 * @author: xha
 * @date: 2021/1/4 16:56
 * @Description: 压缩图片页面
 */
class CompressActivity : MyBaseActivity() {

    var fileUri: Uri? = null


    companion object {
        @JvmStatic
        fun start(
            context: Activity
        ) {
            val starter = Intent(context, CompressActivity::class.java)
            context.startActivity(starter)
        }
    }
    override fun getLayoutId(): Int? {
        return R.layout.activity_compress
    }

    override fun initOnCreate() {

    }

    override fun initOnClickerListener() {
        super.initOnClickerListener()
        tvChooseCompress.setOnClickListenerWithTrigger {
            checkAlbumPermission(this, 101)
        }

        tvComCompress.setOnClickListenerWithTrigger {

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                101 -> {
                    fileUri = data?.data
                    if (fileUri != null) {
                        com.princess.demok.utils.ImageUtils.loadUri(ivChooseCompress, fileUri)
                    }
                }
            }
        }
    }


    /**
     *检查读写权限
     */
    fun checkAlbumPermission(activity: Activity, reqCode: Int) {

        if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                reqCode
            );
        } else {
            openAlbum(activity, reqCode)
        }
    }

    /**
     * 打开图库
     */
    private fun openAlbum(activity: Activity, reqCode: Int) {
        val intent = Intent()
        intent.action = Intent.ACTION_PICK
        intent.type = "image/*"
        activity.startActivityForResult(intent, reqCode)
    }


}